#include "../../core/pch.h"
#include "../../pi/BinarySemaphore.h"

/**
 * Implementation of System V semaphores.
 */

int BinarySemaphore::Create(SemaphoreId& semId)
{
	semId = semget(IPC_PRIVATE, 1, S_IRUSR | S_IWUSR);
}

int BinarySemaphore::Init(SemaphoreId semId)
{
	union semun arg;
	unsigned short values[1];
	values[0] = 1;
	arg.array = values;
	return semctl(semId, 0, SETALL, arg);
}

int BinarySemaphore::Destroy(SemaphoreId semId)
{
	union semun ignoredArg;
	return semctl(semId, 1, IPC_RMID, ignoredArg);
}

int BinarySemaphore::Increment(SemaphoreId semId)
{
	struct sembuf operations[1];
	operations[0].sem_num = 0;
	operations[0].sem_op = 1;
	operations[0].sem_flg = SEM_UNDO;

	return semop(semId, operations, 1);
}

int BinarySemaphore::Decrement(SemaphoreId semId)
{
	struct sembuf operations[1];
	operations[0].sem_num = 0;
	operations[0].sem_op = -1;
	operations[0].sem_flg = SEM_UNDO;

	return semop(semId, operations, 1);
}
